/**
 * Created by lijizhuang on 16/9/14.
 */
define(['jquery', 'underscore', 'backbone', 'modules/settings/account/employeeInfo', 'modules/settings/account/modal/newEmployeeAccount', 'text!modules/settings/account/employeesInfoView.html'],
    function ($, _, Backbone, EmployeeInfoView, NewEmployeeAccountView, EmployeesInfoViewTemplate) {
        var employeesInfoView = Backbone.View.extend({
            tagName: 'div',
            className: 'employeeInfo',
            template: _.template(EmployeesInfoViewTemplate),

            initialize: function (attrs) {
                this.collection.on({
                    'add': _.bind(function(model, collection, options){
                        this.render();
                    }, this),
                    'remove': _.bind(function(model, collection, options){
                        this.render();
                    }, this),
                    'change': _.bind(function (model, collection, options) {
                        this.render();
                    }, this),
                });

                this.options = attrs;
            },

            events:{
                'click #addEmployee': 'onAddEmployeeClick'
            },

            onAddEmployeeClick: function (e) {
                var ownerId = this.options.ownerId;
                var newEmployeeView = new NewEmployeeAccountView({ model: ownerId, collection: this.collection });
                if ($('body').find('#newEmployeeAccount').length === 0) {
                    $('body').append(newEmployeeView.render().el);
                }
                else {
                    $('#newEmployeeAccount').replaceWith(newEmployeeView.render().el);
                }

                $("#newEmployeeAccount").modal({ backdrop: 'static', keyboard: false });
            },

            render: function () {
                //遍历每个员工信息
                this.$el.html(this.template);

                this.collection.each(_.bind(function (employeeInfo) {
                    var employeeInfoView = new EmployeeInfoView({model: employeeInfo, collection:this.collection});
                    this.$el.find('.employeeTable').find('tbody').append(employeeInfoView.render().el);
                    if(employeeInfo.get('enabled') === false){
                        employeeInfoView.$el.addClass('rowDisabled');
                        employeeInfoView.$el.find('td input[type=checkbox]').attr("disabled", true);
                    }
                    else{
                        employeeInfoView.$el.removeClass('rowDisabled');
                        employeeInfoView.$el.find('td input[type=checkbox]').attr("disabled", false);
                    }
                }, this));

                return this;
            }
        });

        return employeesInfoView;
    });